package andy.demo.parseXML.pull;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Xml;
import andy.demo.parseXML.sax.domain.Person;

public class PULLService {

	public static ArrayList<Person>  readXML(InputStream in ) {
		ArrayList<Person> personList = new ArrayList<Person>();
		Person person = null;
		
		try {
			XmlPullParser xmlPullParser = Xml.newPullParser();
			
			xmlPullParser.setInput(in, "utf-8");
			
			int eventType = xmlPullParser.getEventType();
			
			while(eventType != XmlPullParser.END_DOCUMENT) {
				
				switch(eventType) {
				case XmlPullParser.START_TAG: {
					//获取当前的标签
					String tag = xmlPullParser.getName();
					if(tag.equalsIgnoreCase("person")) {
						person = new Person();
						person.setId(Integer.parseInt(xmlPullParser.getAttributeValue(0)) );
						
					}else if(person !=null) {
						if(tag.equalsIgnoreCase("name")) {
							person.setPersonName(xmlPullParser.nextText());
						}else if(tag.equalsIgnoreCase("age")) {
							person.setAge(xmlPullParser.nextText());
						}
					}
					
				}
				break;
				case XmlPullParser.END_TAG: {
					String tag = xmlPullParser.getName();
					if("person".equalsIgnoreCase(tag) && person != null) {
						personList.add(person);
						person = null;
					}
				}
				break;
				}
				
				 //如果xml没有结束，则导航到下一个person节点
				eventType = xmlPullParser.next();
			}
			
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return personList;
		
	}
}
